package com.ghck.shop.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;
import com.ghck.server.exception.ErrorConstant;
import com.ghck.shop.constant.FlowType;
import com.ghck.shop.constant.GoodStatus;
import com.ghck.shop.dao.ChangePriceLogMapper;
import com.ghck.shop.dao.FlowWaterMapper;
import com.ghck.shop.dao.GoodsMapper;
import com.ghck.shop.dao.GoodsSpecificationMapper;
import com.ghck.shop.dao.MakerFlowWaterMapper;
import com.ghck.shop.dao.OrderMapper;
import com.ghck.shop.dao.ShopFlowWaterMapper;
import com.ghck.shop.exception.ShopServerException;
import com.ghck.shop.model.ChangePriceLog;
import com.ghck.shop.model.FlowWater;
import com.ghck.shop.model.Goods;
import com.ghck.shop.model.GoodsConstant;
import com.ghck.shop.model.GoodsSpecification;
import com.ghck.shop.model.ImputedPrice;
import com.ghck.shop.model.MakerFlowWater;
import com.ghck.shop.model.OrderConstant;
import com.ghck.shop.model.OrderDetail;
import com.ghck.shop.model.OrderInfo;
import com.ghck.shop.model.ShippingChannels;
import com.ghck.shop.model.ShopFlowWater;
import com.ghck.shop.model.UserAddress;
import com.ghck.shop.model.UserInvoice;
import com.ghck.shop.model.request.OrderInfoReq;
import com.ghck.shop.model.response.GoodsRes;
import com.ghck.shop.model.response.OrderDetailsRes;
import com.ghck.shop.model.response.OrderInfoRes;
import com.ghck.shop.model.response.UserDefaultAddressInvoice;
import com.ghck.shop.service.FlowService;
import com.ghck.shop.service.GoodsService;
import com.ghck.shop.service.OrderService;
import com.ghck.shop.service.UserAddressService;
import com.ghck.shop.utils.DateUtils;
import com.ghck.shop.utils.FileStoreUtil;
import com.ghck.shop.utils.StringUtil;


/** 
 * @author 作者 : chenxuan
 * @version 创建时间：2016年1月6日 上午9:38:29 
 * 类说明 
 */
@Service
public class OrderServiceImpl implements OrderService{
	
	private final static Logger LOGGER = LoggerFactory.getLogger(OrderServiceImpl.class);

	
	@Autowired
	private OrderMapper orderMapper;
	@Autowired
	private GoodsService goodsService;
	@Autowired
	private UserAddressService userAddressService;
	@Autowired
	private GoodsMapper goodsMapper;
	@Autowired
	private MakerFlowWaterMapper makerFlowWaterMapper;
	@Autowired
	private ShopFlowWaterMapper shopFlowWaterMapper;
	@Autowired
	private GoodsSpecificationMapper goodsSpecificationMapper;
	@Autowired
	private ChangePriceLogMapper changePriceLogMapper;
	@Autowired
	private FlowWaterMapper flowWaterMapper;
	
	@Autowired
	private FlowService flowService;
	
	@Override
	@Transactional(rollbackFor=Exception.class)
	public OrderInfoRes createOrder(OrderInfoReq orderInfoReq) {
		if(orderInfoReq.getUserId() == null || orderInfoReq.getUserId() == 0){
			throw new ShopServerException(ErrorConstant.OPERATION_ERROR.getErrorCode(), "用户ID不能为空");
		}
		if(orderInfoReq.getOrderDetails() == null || orderInfoReq.getOrderDetails().isEmpty()){
			throw new ShopServerException(ErrorConstant.OPERATION_ERROR.getErrorCode(), "商品ID不能为空");
		}
		//商品总购买数量 
		Integer goodsNumber = 0;
		//用户收货地址,如果有实体商品时会赋值
		UserAddress userAddress = null;
		String orderTitle = null;
		String orderImg = null;
		//是否有实体商品
		List<OrderDetail> orderDetails = new ArrayList<OrderDetail>();
		//订单实体
		OrderInfoRes orderInfo = new OrderInfoRes();
		
		for(OrderDetail od : orderInfoReq.getOrderDetails()){
			OrderDetail orderDetail = new OrderDetail();
			boolean addressFlag = false;
			//订单类型
			if(od.getGoodsNumber() == null || od.getGoodsNumber() == 0){
				throw new ShopServerException(ErrorConstant.OPERATION_ERROR.getErrorCode(), "购买数量不能为空");
			}
			goodsNumber += od.getGoodsNumber();
			Integer specificationId = od.getSpecificationId();
			GoodsSpecification gs = null;
			if(specificationId !=null && specificationId > 0){//规格不为空
				gs = goodsSpecificationMapper.findGoodsSpecificationById(specificationId);
				if(gs == null){
					throw new ShopServerException(ErrorConstant.OPERATION_ERROR.getErrorCode(), "该商品规格不存在");
				}
			}
			Goods goods = goodsMapper.getGoodsDetailById(od.getGoodsId());
			if(goods == null){
				throw new ShopServerException(ErrorConstant.OPERATION_ERROR.getErrorCode(), "该商品不存在");
			}
			
			if(orderImg == null){
				orderImg = goods.getThumbnailImage();
			}
			
			orderTitle = goods.getTitle();
			if(!(goods.getIsOnsale() == GoodStatus.on_sale || goods.getIsOnsale() == GoodStatus.review_success)){
				throw new ShopServerException(ErrorConstant.OPERATION_ERROR.getErrorCode(), "该商品还未上架");
			}
			//检查库存 并扣减库存
			goodsService.subtractStock(od.getGoodsId(), od.getGoodsNumber());
			
			orderDetail.setGoodsId(goods.getId());//商品ID
			if(gs != null){
				orderDetail.setGoodsName(goods.getTitle().concat(" ").concat(gs.getName()));//商品名称
				orderDetail.setSalePrice(gs.getSalePrice());//交易价格
				orderDetail.setMarketPrice(gs.getMarketPrice());//市场价
				orderDetail.setSpecificationId(gs.getId());
				Integer realPrice = (gs.getSalePrice() * od.getGoodsNumber());
				orderDetail.setRealPrice(realPrice);//该商品实际总价
			}else {
				orderDetail.setGoodsName(goods.getTitle());//商品名称
				orderDetail.setSpecificationId(0);
				orderDetail.setSalePrice(goods.getSalePrice());//交易价格
				orderDetail.setMarketPrice(goods.getMarketPrice());//市场价
				Integer realPrice = (goods.getSalePrice() * od.getGoodsNumber());
				orderDetail.setRealPrice(realPrice);//该商品实际总价
			}
			orderDetail.setGoodsNumber(od.getGoodsNumber());//购买数量
			orderDetail.setThumbnailImage(goods.getThumbnailImage());
			
			//查询收货地址 并且配送
			if(!addressFlag && goods.getIsExpress().intValue() == GoodsConstant.GOODS_EXPRESS.getStatus().intValue()){
				//判断收货地址ID是否为空
				if(orderInfoReq.getUserAddressId() == null || orderInfoReq.getUserAddressId() ==0){
					throw new ShopServerException(ErrorConstant.OPERATION_ERROR.getErrorCode(), "用户收货地址不能为空");
				}
				
				userAddress = userAddressService.getUserAddressById(orderInfoReq.getUserAddressId());
				if(userAddress == null ){
					throw new ShopServerException(ErrorConstant.OPERATION_ERROR.getErrorCode(), "未查询到用户收货地址");
				}else{
					addressFlag = true;
				}
			}
			orderDetail.setIsService(0);//服务
			orderDetail.setIsReal(1);//实体商品
			orderInfo.setGoodsType(goods.getGoodsType());
		
			orderDetails.add(orderDetail);
		}
		//保存订单详情
		if(orderDetails.isEmpty()){
			throw new ShopServerException(ErrorConstant.OPERATION_ERROR.getErrorCode(), "保存订单,订单详情不能为空");
		}
		
		String orderNo = StringUtil.generateOrderNO();
		orderInfo.setOrderNo(orderNo);//订单编号
		orderInfo.setUserId(orderInfoReq.getUserId());
		orderInfo.setOrderStatus(OrderConstant.ORDER_STATUS_CONFIRMED.getOrderStatus());//订单状态 默认为已确认
		
		orderInfo.setReceiver(userAddress.getName());
		orderInfo.setProvince(userAddress.getProvince());
		orderInfo.setCity(userAddress.getCity());
		orderInfo.setDistrict(userAddress.getDistrict());
		orderInfo.setAddress(userAddress.getAddress());
		orderInfo.setPostcode(userAddress.getPostcode());
		orderInfo.setTel(userAddress.getTel());
		orderInfo.setMobile(userAddress.getMobile());
		//购买物品数量 
		orderInfo.setGoodsNumber(goodsNumber);
		
		//订单金额 （购物数量 * 商品交易金额）
		//计算价格
		ImputedPrice imputedPrice = calculatePostage(orderInfoReq);
		LOGGER.info("计算价格:{}", JSONObject.toJSONString(imputedPrice));
		
		//订单总金额 订单金额 + 运费 - 优惠券金额
		orderInfo.setOrderTitle(orderTitle);
		orderInfo.setOrderImg(orderImg);
		orderInfo.setCouponId(orderInfoReq.getCouponId());
		orderInfo.setCouponAmount(imputedPrice.getCouponAmount());//优惠金额
		orderInfo.setOrderPayee(imputedPrice.getOrderAmount());//商品总金额
		orderInfo.setShippingPayee(imputedPrice.getPostageAmount());//邮费
		orderInfo.setTotalPayee(imputedPrice.getTotalAmount());//总金额
		//如果开发票
		if(orderInfoReq.getIsInvoice() != null && orderInfoReq.getIsInvoice() == 1){
			//发票金额 = 订单金额 - 优惠券金额
			Integer invoiceAmount = imputedPrice.getOrderAmount() - orderInfo.getCouponAmount();
			if(invoiceAmount < 0){
				invoiceAmount = 0;
			}
			orderInfo.setInvoiceAmount(invoiceAmount);
			orderInfo.setIsInvoice(orderInfoReq.getIsInvoice());
			UserInvoice ui = orderMapper.getUserInvoiceByTitle(orderInfoReq.getInvoiceTitle());
			if(ui == null){
				UserInvoice userInvoice = new UserInvoice();
				userInvoice.setUserId(orderInfoReq.getUserId());
				userInvoice.setTitle(orderInfoReq.getInvoiceTitle());
				orderMapper.createUserInvoice(userInvoice);
				orderInfo.setInvoiceId(userInvoice.getId());
			}else{
				orderInfo.setInvoiceId(ui.getId());
			}
			
		}else{
			orderInfo.setIsInvoice(0);
			orderInfo.setInvoiceAmount(0);
		}
		//如果订单总金额为0，则订单为已支付
		if(orderInfo.getTotalPayee() == 0){
			orderInfo.setPayStatus(OrderConstant.PAY_STATUS_PREPAID.getOrderStatus());
			orderInfo.setPayTime(DateUtils.getCurrentDate());
		}
		else{
			orderInfo.setPayStatus(OrderConstant.PAY_STATUS_NON_PAYMENT.getOrderStatus());
		}
		//买家留言
		orderInfo.setBuyerMemo(orderInfoReq.getBuyerMemo());
		//订单来源
		orderInfo.setSource(orderInfoReq.getSource());
		Date createTime = DateUtils.getCurrentDate();
		orderInfo.setExpirationTime(DateUtils.addDay(createTime, 1));
		//保存订单
		orderMapper.createOrderInfo(orderInfo);
		//0 系统订单 1:商家订单
		if("0".equals(orderInfoReq.getOrderType())){//0为系统商品，代理人可以获取提成
			//每单子总提成 = （成交价-成本价=差价提成） + （成本份 * 返点系数 = 返点提成）
			//保存代理人
			flowService.addMakerFlowWater(imputedPrice.getProxyAmount(), orderInfoReq.getSupplierUserId(), orderInfoReq.getUserId(), orderInfo.getId());
		}else if("1".equals(orderInfoReq.getOrderType())){
			ShopFlowWater shopFlowWater = new ShopFlowWater();
			shopFlowWater.setShopUserId(orderInfoReq.getSupplierUserId());
			shopFlowWater.setOrderId(orderInfo.getId());
			shopFlowWater.setUserId(orderInfoReq.getUserId());
			shopFlowWaterMapper.saveShopFlowWater(shopFlowWater);
		}
		
		orderMapper.batchCreateOrderDetail(orderDetails,orderInfo.getId());
		OrderInfoRes oi = new OrderInfoRes();
		OrderInfoRes orderInfoRes = orderMapper.getOrderById(orderInfo.getId());
		oi.setOrderStatus(orderInfoRes.getOrderStatus());
		oi.setOrderNo(orderInfo.getOrderNo());
		oi.setId(orderInfo.getId());
		oi.setTotalPayee(orderInfo.getTotalPayee());
		return oi;
	}

	@Override
	public void cancelOrder(OrderInfoReq orderInfoReq) {
		
		if(orderInfoReq.getId() == null || orderInfoReq.getId() == 0){
			throw new ShopServerException(ErrorConstant.PARAM_ERROR.getErrorCode(), "订单ID不能为空");
		}
		OrderInfo orderInfo = orderMapper.getOrderById(orderInfoReq.getId());
		if(null == orderInfo){
			throw new ShopServerException(ErrorConstant.OPERATION_ERROR.getErrorCode(), "订单不存在");
		}
		if(orderInfoReq.getUserId().intValue() != orderInfo.getUserId().intValue()){
			throw new ShopServerException(ErrorConstant.OPERATION_ERROR.getErrorCode(), "该订单不属于您,不能取消");
		}
		//已支付不能取消
		if(orderInfo.getOrderStatus() == OrderConstant.PAY_STATUS_PREPAID.getOrderStatus()){
			throw new ShopServerException(ErrorConstant.OPERATION_ERROR.getErrorCode(), "订单已支付，不可取消.");
		}
		//已发货不可取消
		if(orderInfo.getOrderStatus() == OrderConstant.SHIPPING_STATUS_SHIPPED.getOrderStatus()){
			throw new ShopServerException(ErrorConstant.OPERATION_ERROR.getErrorCode(), "订单已发货不可取消.");
		}
		//已收货不可取消
		if(orderInfo.getOrderStatus() == OrderConstant.SHIPPING_STATUS_RECEIVED.getOrderStatus()){
			throw new ShopServerException(ErrorConstant.OPERATION_ERROR.getErrorCode(), "订单已收货不可取消.");
		}
		//已完成订单不可取消
		if(orderInfo.getOrderStatus() == OrderConstant.ORDER_STATUS_COMPLETED.getOrderStatus()){
			throw new ShopServerException(ErrorConstant.OPERATION_ERROR.getErrorCode(), "订单已完成不可取消.");
		}
		//已过期不可取消
		if(orderInfo.getOrderStatus() == OrderConstant.ORDER_STATUS_EXPIRED.getOrderStatus()){
			throw new ShopServerException(ErrorConstant.OPERATION_ERROR.getErrorCode(), "订单已过期不可取消.");
		}
		List<OrderDetailsRes> orderDetails = orderMapper.getOrderDetailList(orderInfoReq.getId());
		for(OrderDetailsRes or : orderDetails){
			goodsService.increaseStock(or.getGoodsId(), or.getGoodsNumber());
		}
		orderMapper.cancelOrderInfo(orderInfoReq.getId(), OrderConstant.ORDER_STATUS_CANCELED.getOrderStatus());
		
	}

	@Override
	public void confirmReceipt(OrderInfoReq orderInfoReq) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void paySuccessCallback(String orderNo, String payChannel,
			String buyerAccount, String chId) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public ImputedPrice calculatePostage(OrderInfoReq orderInfoReq) {
		if(orderInfoReq.getOrderDetails() == null || orderInfoReq.getOrderDetails().isEmpty()){
			throw new ShopServerException(ErrorConstant.OPERATION_ERROR.getErrorCode(), "购买商品不能为空");
		}
		ImputedPrice imputedPrice = new ImputedPrice();
		Integer orderPrice = 0;
		Integer marketPrice = 0;
		Integer postPrice = 0;
		Integer proxyPrice = 0;
		List<Goods> goodsList = new ArrayList<Goods>();
		for(OrderDetail od :  orderInfoReq.getOrderDetails()){
			if(od.getGoodsNumber() == null || od.getGoodsNumber() <= 0){
				throw new ShopServerException(ErrorConstant.OPERATION_ERROR.getErrorCode(), "购买数量不能为空");
			}
			if(od.getGoodsId() == null){
				throw new ShopServerException(ErrorConstant.OPERATION_ERROR.getErrorCode(), "商品ID不能为空");
			}
			Goods good = new Goods();
			Integer specificationId = od.getSpecificationId();
			GoodsSpecification gs = null;
			if(specificationId !=null && specificationId > 0){//规格不为空
				gs = goodsSpecificationMapper.findGoodsSpecificationById(specificationId);
				if(gs == null){
					throw new ShopServerException(ErrorConstant.OPERATION_ERROR.getErrorCode(), "该商品规格不存在");
				}
			}
			GoodsRes goodsRes = goodsService.goodsDetailById(od.getGoodsId());
			if(goodsRes == null){
				throw new ShopServerException(ErrorConstant.OPERATION_ERROR.getErrorCode(), "商品不存在");
			}
			postPrice = postPrice > goodsRes.getPostFree() ? postPrice:goodsRes.getPostFree();
			if(gs != null){
				//计算代理费用 交易价 - 成本价 + 交易价 * 提成比率
				LOGGER.info("SalePrice:{} CostPrice:{}",gs.getSalePrice(),gs.getCostPrice());
				//交易价 - 成本价
				Integer proxyll = gs.getSalePrice() - gs.getCostPrice();
				LOGGER.info("proxyll:{}",proxyll);
				// 交易价  * 提成比率
				proxyll = (proxyll + (gs.getSalePrice() * gs.getPercentageRate())/100);
				LOGGER.info("PercentageRate:{}", gs.getPercentageRate());
				LOGGER.info("proxyll:{}", proxyll);
//				proxyPrice = (int) (proxyPrice + proxyll);
				proxyPrice = proxyPrice + (proxyll * od.getGoodsNumber());
				Integer price = gs.getSalePrice() * od.getGoodsNumber();
				orderPrice += price;
				Integer mPrice = gs.getMarketPrice() * od.getGoodsNumber();
				marketPrice += mPrice;
				good.setId(od.getGoodsId());
				good.setType(od.getType());
				goodsList.add(good);
			}else {
				Integer proxyll = goodsRes.getSalePrice() - goodsRes.getCostPrice();
				LOGGER.info("proxyPrice:{}", proxyll);
				proxyll = (proxyll + (goodsRes.getCostPrice() * goodsRes.getPercentageRate())/100);
				LOGGER.info("proxyPrice:{}", proxyll);
//				proxyPrice = (int) (proxyPrice + proxyll);
				proxyPrice = proxyPrice + (proxyll * od.getGoodsNumber());
				Integer price = goodsRes.getSalePrice() * od.getGoodsNumber();
				orderPrice += price;
				Integer mPrice = goodsRes.getMarketPrice() * od.getGoodsNumber();
				marketPrice += mPrice;
				good.setId(od.getGoodsId());
				good.setType(od.getType());
				goodsList.add(good);
			}
		}
		imputedPrice.setOrderAmount(orderPrice);
		imputedPrice.setProxyAmount(proxyPrice);
		imputedPrice.setMarketPrice(marketPrice);
		if(orderInfoReq.getUserAddressId() == null || orderInfoReq.getUserAddressId() == 0){
			throw new ShopServerException(ErrorConstant.OPERATION_ERROR.getErrorCode(), "收货地址ID不能为空");
		}
		UserAddress userAddress = userAddressService.getUserAddressById(orderInfoReq.getUserAddressId());
		if(null == userAddress){
			throw new ShopServerException(ErrorConstant.OPERATION_ERROR.getErrorCode(), "用户地址不存在");
		}
		//邮费
		imputedPrice.setPostageAmount(postPrice);
		
		//订单总价 = 商品总价 + 运费 - 优惠券
		Integer totalAmount = imputedPrice.getOrderAmount().intValue() + imputedPrice.getPostageAmount().intValue() - imputedPrice.getCouponAmount().intValue();
		if(totalAmount < 0){
			totalAmount = 0;
		}
		imputedPrice.setTotalAmount(totalAmount);
		return imputedPrice;
	}

	@Override
	public void callWebhookPayrSuccess(String orderNo) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public OrderInfoRes generageOrder(OrderInfoReq orderInfoReq) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List<OrderInfoRes> userOrderList(OrderInfoReq orderInfoReq) {
		if(orderInfoReq.getUserId() == null){
			throw new ShopServerException(ErrorConstant.OPERATION_ERROR.getErrorCode(), "用户ID不能为空");
		}
		List<OrderInfoRes> list =  orderMapper.userOrderList(orderInfoReq);
		convertOrderInfo(list);
		return list;
	}
	
	@Override
	public List<OrderInfoRes> adminOrderList(OrderInfoReq orderInfoReq) {
		List<OrderInfoRes> list =  orderMapper.adminOrderList(orderInfoReq);
		convertOrderInfo(list);
		return list;
	}
	@Override
	public Integer countAdminOrderList(OrderInfoReq orderInfoReq) {
		return orderMapper.countAdminOrderList(orderInfoReq);
	}

	private void convertOrderInfo(List<OrderInfoRes> list) {
		if(CollectionUtils.isNotEmpty(list)){
			List<Integer> orderIds = new ArrayList<Integer>();
			for(OrderInfoRes oir : list){
				if(StringUtils.isNotEmpty(oir.getOrderImg())){
					oir.setOrderImg(FileStoreUtil.getBaseUrl().concat(oir.getOrderImg()));
				}
				orderIds.add(oir.getId());
			}
			List<OrderDetailsRes> ods = orderMapper.batchFindOrderDetails(orderIds);
			Map<Integer, List<OrderDetailsRes>> map = new HashMap<Integer, List<OrderDetailsRes>>();
			for(OrderDetailsRes od:ods){
				if(StringUtils.isNotEmpty(od.getThumbnailImage())){
					od.setThumbnailImage(FileStoreUtil.getBaseUrl().concat(od.getThumbnailImage()));
				}
				List<OrderDetailsRes> temp = map.get(od.getOrderId());
				if(temp == null){
					temp = new ArrayList<OrderDetailsRes>();
					map.put(od.getOrderId(), temp);
				}
				temp.add(od);
			}
			for(OrderInfoRes oir : list){
				if(map.containsKey(oir.getId())){
					oir.setOrderDetails(map.get(oir.getId()));
				}
			}
			
		}
	}
	
	@Override
	public List<OrderInfoRes> makerOrderList(OrderInfoReq orderInfoReq) {
		List<MakerFlowWater> mfws = flowService.getMakerFlowWatersList(orderInfoReq.getUserId(), orderInfoReq.getStart(), orderInfoReq.getLimit());
		if(CollectionUtils.isNotEmpty(mfws)){
			List<Integer> orderIds = new ArrayList<Integer>();
			for(MakerFlowWater makerFlowWater:mfws){
				orderIds.add(makerFlowWater.getOrderId());
			}
			List<OrderInfoRes> list =  orderMapper.makerOrderList(orderInfoReq, orderIds);
			convertOrderInfo(list);
			return list;
		}
		return new ArrayList<OrderInfoRes>();
	}

	@Override
	public List<OrderInfoRes> sellerOrderList(OrderInfoReq orderInfoReq) {
		List<ShopFlowWater> mfws = shopFlowWaterMapper.listShopFlowWater(orderInfoReq.getUserId(), orderInfoReq.getStart(), orderInfoReq.getLimit());
		if(CollectionUtils.isNotEmpty(mfws)){
			List<Integer> orderIds = new ArrayList<Integer>();
			for(ShopFlowWater makerFlowWater:mfws){
				orderIds.add(makerFlowWater.getOrderId());
			}
			List<OrderInfoRes> list =  orderMapper.makerOrderList(orderInfoReq, orderIds);
			convertOrderInfo(list);
			return list;
		}
		return new ArrayList<OrderInfoRes>();
	}
	
	
	

	@Override
	public OrderInfoRes orderDetail(OrderInfoReq orderInfoReq) {
		
		if(orderInfoReq.getUserId() == null || orderInfoReq.getUserId() ==0){
			//throw new ShopServerException(ErrorConstant.PARAM_ERROR.getErrorCode(), "用户ID不能为空");
		}
		if(orderInfoReq.getId() == null || orderInfoReq.getId() ==0){
			throw new ShopServerException(ErrorConstant.PARAM_ERROR.getErrorCode(), "订单ID不能为空");
		}
		OrderInfoRes order = orderMapper.getOrderById(orderInfoReq.getId());
		if(null == order){
			throw new ShopServerException(ErrorConstant.PARAM_ERROR.getErrorCode(), "订单不存在");
		}
		order.setOrderImg(FileStoreUtil.getBaseUrl().concat(order.getOrderImg()));
		//order.setOrderImg(FileStoreUtil.getBaseUrl().concat(order.getOrderImg()));
		/**
		if(orderInfoReq.getUserId().intValue() != order.getUserId().intValue()){
			throw new ShopServerException(ErrorConstant.PARAM_ERROR.getErrorCode(), "该订单不属于您,不能查看");
		}**/
		//获取详查详情
		List<OrderDetailsRes> orderDetails = orderMapper.getOrderDetailList(orderInfoReq.getId());
		for(OrderDetailsRes odr : orderDetails){
			GoodsRes goods = goodsMapper.getGoodsDetailById(odr.getGoodsId());
			odr.setMarketPrice(goods.getMarketPrice());
			odr.setSubject(goods.getSubject());
			odr.setThumbnailImage(FileStoreUtil.getBaseUrl().concat(goods.getThumbnailImage()));
			if(odr.getSpecificationId() != null && odr.getSpecificationId()  > 0 ){
				GoodsSpecification goodsSpecification = goodsSpecificationMapper.findGoodsSpecificationById(odr.getSpecificationId());
				if(null != goodsSpecification){
					odr.setSpecificationName(goodsSpecification.getName());
				}
			}
		}
		order.setOrderDetails(orderDetails);
		return order;
	}

	@Override
	public OrderInfo getOrderInfoById(Integer orderId) {
		
		return orderMapper.getOrderById(orderId);
	}

	@Override
	public OrderInfo checkOrderCouldPay(Integer orderId) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public OrderInfoRes getOrderInfoByOrderNo(OrderInfoReq orderInfoReq) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public OrderInfoRes getOrderInfoByOrderNo(String orderNo) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public UserDefaultAddressInvoice getUserDefaultAddressInvoice(Integer userId) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List<OrderDetailsRes> getOrderDetailsList(Integer orderId) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	@Transactional
	public void webhookPayrSuccessCallBack(String orderNo, String channel, String buyerAccount, String chId) {
		LOGGER.info("订单no:{}完成支付", orderNo);
		orderMapper.updateOrderPaySuccessForReal(orderNo, channel, OrderConstant.PAY_STATUS_PREPAID.getOrderStatus(), chId);
		//TODO 1、代理人加钱
		OrderInfo oi = orderMapper.getOrderByOrderNo(orderNo);
		LOGGER.info("具体订单信息:{}", JSONObject.toJSONString(oi));
		if(oi!=null){
			MakerFlowWater makerFlowWater = flowService.getMakerFlowWaterByOrderId(oi.getId());
			if(makerFlowWater != null){
				flowService.updateMakerFlowWaterComplete(makerFlowWater.getId());
				FlowWater fw = new FlowWater();
				fw.setUserId(makerFlowWater.getUserId());
				fw.setType(FlowType.ROYALTY_INCOME);
				fw.setPic("");
				fw.setDescribe("订单编号:" + oi.getOrderNo()+"-提成收入");
				fw.setAmount(makerFlowWater.getAmount());
				flowWaterMapper.saveFlowWater(fw);
			}
			ShopFlowWater shopFlowWater = shopFlowWaterMapper.findShopFlowWaterByOrderId(oi.getId());
			if(shopFlowWater !=null){
				shopFlowWaterMapper.updateShopFlowWaterComplete(shopFlowWater.getId());
				FlowWater fw = new FlowWater();
				fw.setUserId(shopFlowWater.getUserId());
				fw.setType(FlowType.SHOP_INCOME);
				fw.setPic("");
				fw.setDescribe("店铺收入-订单号-"+oi.getOrderNo());
				fw.setAmount(oi.getTotalPayee());
				flowWaterMapper.saveFlowWater(fw);
			}
			Integer buyUserId = oi.getUserId();
			FlowWater fw = new FlowWater();
			fw.setUserId(buyUserId);
			fw.setType(1);
			fw.setPic("");
			fw.setDescribe("购物");
			fw.setAmount(-oi.getTotalPayee());
			flowWaterMapper.saveFlowWater(fw);
		}
		
	}

	@Override
	@Transactional
	public void changeOrderGoodPrice(Integer userId, Integer orderId,Integer orderDetailId, Integer newPrice) {
		OrderInfoRes ois = orderMapper.getOrderById(orderId);
		if(ois==null){
			throw new ShopServerException(ErrorConstant.PARAM_ERROR.getErrorCode(), "该订单不存在");
		}
		OrderDetailsRes ods = orderMapper.findOrderDetailsResById(orderDetailId);
		if(ods == null || ods.getOrderId().intValue() != orderId){
			throw new ShopServerException(ErrorConstant.PARAM_ERROR.getErrorCode(), "该订单商品不存在");
		}
		
		//1、修改orderdetail
		orderMapper.updateOrderDetailById(orderDetailId, newPrice);
		Integer oldGoodPrice = ods.getRealPrice();
		Integer newGoodPrice = newPrice*ods.getGoodsNumber();
		//2、修改订单价格
		orderMapper.updateOrderPrice(orderId, (newGoodPrice-oldGoodPrice));
		
		//3、修改代理人提成
		MakerFlowWater makerFlowWater = flowService.getMakerFlowWaterByOrderId(orderId);
		Integer specificationId = ods.getSpecificationId();
		if(specificationId != null && specificationId > 0){//有规格的商品
			if(makerFlowWater != null){
				int old = 0;
				int newP = 0;
				GoodsSpecification goodsSpecification = goodsSpecificationMapper.findGoodsSpecificationById(ods.getSpecificationId());
				double newproxyll = newPrice- goodsSpecification.getCostPrice();
				newproxyll = (newproxyll + (goodsSpecification.getCostPrice() * goodsSpecification.getPercentageRate())/100);
				old = ((int) (old + newproxyll))*ods.getGoodsNumber();
				
				double oldproxyll = ods.getSalePrice() - goodsSpecification.getCostPrice();
				oldproxyll = (oldproxyll + (goodsSpecification.getCostPrice() * goodsSpecification.getPercentageRate())/100);
				newP = ((int) (newP + oldproxyll))*ods.getGoodsNumber();
				flowService.updateMakerFlowWaterAmount(makerFlowWater.getId(), (int)(newproxyll-oldproxyll));
			}
		}else {
			int old = 0;
			int newP = 0;
			Goods good = goodsMapper.getGoodsDetailById(ods.getGoodsId());
			double newproxyll = newPrice- good.getCostPrice();
			newproxyll = (newproxyll + (good.getCostPrice() * good.getPercentageRate())/100);
			old = ((int) (old + newproxyll))*ods.getGoodsNumber();
			
			double oldproxyll = ods.getSalePrice() - good.getCostPrice();
			oldproxyll = (oldproxyll + (good.getCostPrice() * good.getPercentageRate())/100);
			newP = ((int) (newP + oldproxyll))*ods.getGoodsNumber();
			flowService.updateMakerFlowWaterAmount(makerFlowWater.getId(), (int)(newproxyll-oldproxyll));
		}
		ChangePriceLog changePriceLog = new ChangePriceLog();
		changePriceLog.setAfterPrice(newPrice);
		changePriceLog.setBeforePrice(ods.getSalePrice());
		changePriceLog.setOperateUserId(userId);
		changePriceLog.setOrderDetailId(orderDetailId);
		changePriceLogMapper.saveChangePriceLog(changePriceLog);
	}

	@Override
	public List<ShippingChannels> getAllShippingChannels() {
		
		return orderMapper.getAllShippingChannels();
	}

	@Override
	public void updateOrderShippingChannel(OrderInfoReq orderInfoReq) {
		orderMapper.updateOrderShippingChannel(orderInfoReq);
	}
	
}